<?php

namespace App\Http\Controllers\Api;

use App\Services\MaterielTypeService;
use  App\V3\V3_1\Models\StorageManageModel;
use  App\V3\V3_1\Models\MaterielTypeModel;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Http\Request;
use App\Helper\Utils\Util;

class MaterielTypeController extends BaseController
{
    /**
     * @商品列表
     * created 在 2021/10/19 14:11 创建
     * @author SunWu
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
     public function materielTypeList(Request $request)
     {
         //参数验证
         $validator = Validator::make($data = $request->all(), [
             'pageSize' =>'required|integer',//页面大小
             'currentPage' =>'required|integer',//当前页
         ]);

         //参数错误响应
         if ($info = $validator->errors()->first()) {
             return response()->json([
                 'code' => 1,
                 'msg' => $info,
                 'data' => '',
             ]);
         }

         return $this->success(
             MaterielTypeService::materielTypeList(
                 $this->getMainUserId(),
                 $data
             )
         );
     }

     //物料类型随机code
     public function randCode()
     {
         $data['materiel_no'] = Util::randStr(8);

         while(!empty($checkClassNo = MaterielTypeModel::checkMaterielTypeCode($data['materiel_no'], $this->getMainUserId()))) {
             $data['materiel_no'] = Util::randStr(8);
         }

         return $this->success($data);
     }

     /**
      * @新建物料类型
      * created 在 2021/10/30 10:37 创建
      * @author SunWu
      * @param Request $request
      * @return \Illuminate\Http\JsonResponse
      */
     public function add(Request $request)
     {
         $validator = Validator::make($data = $request->all(), [
                 'materiel_name' => 'required',//物料名称
                 // 'materiel_img' => 'required',//物料图
                 'materiel_no' => 'size:8',//物料编号
                 'materiel_class_id' => [
                     'required',
                     'integer',
                     Rule::notIn([0]),
                 ],//物料类型所属二级分类id
             ],
             [
                 'materiel_name.required' => '请填写物料名称',
                 // 'materiel_img.required' => '请上传物料类型图',
                 'materiel_class_id.required' => '请选择物料类型所属分类id',
             ]
         );

         if ($info = $validator->errors()->first()) {
             return response()->json([
                 'code' => 1,
                 'msg' => $info,
                 'data' => '',
             ]);
         }

         $result = MaterielTypeService::add(
                                         $this->getMainUserId(),
                                         $request->all()
                                     );

          if(!$result['code']) {
              $this->log('新建物料类型', $data);
              return $this->success(['id' => $result['data']]);
          }
          else {
              return $this->fail('', $result['msg']);
          }
     }

     /**
      * @删除指定物料类型
      * created 在 2021/10/30 15:32 创建
      * @author SunWu
      * @param Request $request
      * @return \Illuminate\Http\JsonResponse
    */
    public function del(Request $request)
    {
        $materielTypeId = $request->input('id');

        if(empty($materielTypeId)) {
            return fail('', '参数`物料类型id`缺失');
        }

        // $checkMaterielInfo = MaterielsModel::where('type_id', $materielTypeId)->wehre('delete_flag', 0)->first();
        // if(!empty($checkMaterielInfo)) {
        //     return $this->fail('', '若需要删除该物料类型，需删除该类型下所有的采购单数据');
        // }

        //检查库存中是否存在该类型的商品
        $checkTypeInstorage = StorageManageModel::where('type_id', $materielTypeId)
                                            ->where('delete_flag', 0)
                                            ->where('in_storage_num', '!=', '0')
                                            ->first();

        if(!empty($checkTypeInstorage)) {
            return $this->fail('', '若需要删除该物料类型，需删除该类型下所有的在库数据');
        }

        MaterielTypeModel::where('id', $materielTypeId)->update(['delete_flag' => 1]);

        $this->log('删除物料类型', $materielTypeId);
        return $this->success();
     }

     /**
      * @修改指定物料类型信息
      * created 在 2021/11/02 10:52 创建
      * @author SunWu
      * @param Request $request
      * @return \Illuminate\Http\JsonResponse
    */
     public function edit(Request $request)
     {
         $validator = Validator::make($data = $request->all(), [
                'id' => 'required',//物料名称
                'materiel_name' => 'required',//物料名称
                'type_name' => 'required',//物料型号
                // 'materiel_img' => 'required',//物料图
                'materiel_no' => 'required|size:8',//物料编号
                'materiel_class_id' => [
                    'required',
                    'integer',
                    Rule::notIn([0]),
                ],//物料类型所属二级分类id
            ],
            [
                'id.required' => '参数`id`缺失',
                'materiel_name.required' => '请填写物料名称',
                'type_name.required' => '请填写物料型号',
                // 'materiel_img.required' => '请上传物料类型图',
                'materiel_no.required' => '请填写物料编号',
                'materiel_class_id.required' => '请选择物料类型所属分类id',
            ]
        );

        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $result = MaterielTypeService::edit($this->getMainUserId(), $data);

        if($result['code']) {
            return $this->fail('', $result['msg']);
        }
        else {
            $this->log('修改商品类型信息', $data);
            return $this->success();
        }
     }

     /**
      * @物料类型详细信息
      * created 在 2021/11/02 14:12 创建
      * @author SunWu
      * @param Request $request
      * @return \Illuminate\Http\JsonResponse
    */
   public function info(Request $request)
   {
       if(empty($request->input('id'))) {
           $this->fail('', '参数`物料类型id`缺失');
       }

       return $this->success(
           MaterielTypeService::info(
               $request->input('id')
           )
       );
   }

   public function materielTypeSelect(Request $request)
   {
       $keyword = empty($request->keyword)?'':$request->keyword;
       $condition = [];
       if(!empty($request->materiel_class_id)) {
           $condition['a.materiel_class_id'] = ['EQ' => $request->materiel_class_id];
       }

       return $this->success(
           MaterielTypeService::materielTypeSelect(
               $this->getMainUserId(),
               $keyword,
               $condition,
               $request->pageSize,
               $request->currentPage
           )
       );
   }
}
